package com.cc.bsp.domain;

import java.io.Serializable;
import java.util.List;

import com.cc.bsp.domain.exception.DomainException;
import com.cc.bsp.persistence.dao.IQueryPageOrder;
import com.cc.bsp.persistence.dao.IRootDao;
import com.cc.bsp.persistence.entity.IEntity;
import com.cc.bsp.persistence.exception.PersistenceException;

public abstract class BaseDomainRepositoryService implements DomainRepositoryService {

	protected IRootDao<IEntity, Serializable> rootDao;

	public void create(Domain domain) throws DomainException {
		try {
			rootDao.add(domain);
		} catch (PersistenceException e) {
			throw new DomainException(e);
		}
	}

	public void update(Domain domain) throws DomainException {
		try {
			rootDao.update(domain);
		} catch (PersistenceException e) {
			throw new DomainException(e);
		}
	}

	public void delete(Domain domain) throws DomainException {
		try {
			rootDao.delete(domain);
		} catch (PersistenceException e) {
			throw new DomainException(e);
		}
	}

	public Domain findById(Serializable id) throws DomainException {
		try {
			return (Domain) rootDao.findById(id);
		} catch (PersistenceException e) {
			throw new DomainException(e);
		}
	}

	public Domain findOne(Domain domain) throws DomainException {
		try {
			List<IEntity> list = rootDao.findList(domain);
			if (list == null || list.isEmpty()) {
				return null;
			} else {
				return (Domain) list.get(0);
			}
		} catch (PersistenceException e) {
			throw new DomainException(e);
		}
	}

	@SuppressWarnings("unchecked")
	public List<Domain> findList(Domain domain, IQueryPageOrder pageOrder)
			throws DomainException {
		try {
			@SuppressWarnings("rawtypes")
			List list = rootDao.findList(domain, pageOrder);
			return list;
		} catch (PersistenceException e) {
			throw new DomainException(e);
		}
	}

	@SuppressWarnings("unchecked")
	public List<Domain> findAll(IQueryPageOrder pageOrder) throws DomainException {
		try {
			@SuppressWarnings("rawtypes")
			List list = rootDao.findAll(pageOrder);
			return list;
		} catch (PersistenceException e) {
			throw new DomainException(e);
		}
	}

	@SuppressWarnings("unchecked")
	public List<Domain> findList(Domain domain) throws DomainException {
		try {
			@SuppressWarnings("rawtypes")
			List list = rootDao.findList(domain);
			return list;
		} catch (PersistenceException e) {
			throw new DomainException(e);
		}
	}

	@SuppressWarnings("unchecked")
	public List<Domain> findAll() throws DomainException {
		try {
			@SuppressWarnings("rawtypes")
			List list = rootDao.findAll();
			return list;
		} catch (PersistenceException e) {
			throw new DomainException(e);
		}
	}

	public abstract IRootDao<IEntity, Serializable> getRootDao();

}
